package com.neo.controller;

import com.neo.util.FastDFSUtil;
import com.neo.util.IOUtils;
import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.ServerInfo;
import org.csource.fastdfs.StorageServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

@Controller
public class FileController {

    private static Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Autowired
    private IOUtils ioUtils;

    @GetMapping("/download")
    public void singleFileDownLoad(String groupName, String remoteFileName, HttpServletResponse response) {
        //upload file successfully!!!group_name:group1, remoteFileName: M00/00/00/rBDooVwXaOqAUiNxAAHCFl5Cnnc572.jpg                        RedirectAttributes redirectAttributes) {
        groupName = "group1";
        remoteFileName = "M00/00/00/wKgTmVyLGGaAGNjfAAJmz31eXVE601.jpg";
        try {
            InputStream is = fastDFSUtil.downFile(groupName, remoteFileName);
            if(is!=null){
                ioUtils.download(is, remoteFileName, response);
            }
        } catch (Exception e) {
            logger.error("download file failed", e);
        }
    }

    @GetMapping("/delete")
    public void singleFileDelete(String groupName, String remoteFileName, HttpServletResponse response) {
        groupName = "group1";
        remoteFileName = "M00/00/00/wKgTiVwZ7xqAWzmvAAHCFl5Cnnc543.jpg";
        try {
            fastDFSUtil.deleteFile(groupName, remoteFileName);
            System.err.println("delete success ！！！");
        } catch (Exception e) {
            logger.error("download file failed", e);
        }
    }

    @GetMapping("/test")
    public void testfastDFS(String groupName, String remoteFileName, HttpServletResponse response) {
        groupName = "group1";
        remoteFileName = "M00/00/00/wKgTmVyLFdKAGfpUAAJmz31eXVE533.jpg";
        try {
            ServerInfo[] serverInfos= fastDFSUtil.getFetchStorages(groupName,remoteFileName);
            StorageServer[] storageServer=fastDFSUtil.getStoreStorages(groupName);
            FileInfo fileInfo=fastDFSUtil.getFile(groupName,remoteFileName);
            System.err.println("serverInfos==="+serverInfos);
            System.err.println("storageServer==="+storageServer);
            System.err.println("fileInfo==="+fileInfo);
        } catch (Exception e) {
            logger.error("download file failed", e);
        }
    }
}